package upload

import (
	"cms/core/config"
	"fmt"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"mime/multipart"
	"os"
	"path"
	"time"
)

func Save(ctx *gin.Context, file *multipart.FileHeader, dir string) (string, error) {
	now := time.Now()
	dateDir := now.Format("20060102")
	saveDir := path.Join(config.App.UploadPath, dir, dateDir)
	ext := MimeToExt(file.Header.Get("Content-Type"))
	fileName := uuid.NewV4().String() + ext

	root, _ := os.Getwd()
	if err := os.MkdirAll(path.Join(root, saveDir), 0777); err != nil {
		return "", fmt.Errorf("mkdir %s err: %v", saveDir, err)
	}

	outputFile := path.Join(saveDir, fileName)
	dst := path.Join(root, outputFile)

	if err := ctx.SaveUploadedFile(file, dst); err != nil {
		return "", err
	}

	return outputFile, nil
}
